#!/usr/bin/env python
import sqlite3
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading, urllib, json, socket, re
import urlparse
from base64 import standard_b64encode as b64encode
from cookielib import CookieJar, DefaultCookiePolicy
from os.path import basename, isfile, exists
from os import walk
from epublib import epub
#try: from lxml import etree
import xml.etree.ElementTree as etree
from xml.sax.saxutils import escape
import random

class Handler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        self.files = []
        for dirpath, dirnames, filenames in walk("./"):
            self.files = self.files + [f for f in filenames if "." in f]
        self.mybook = False
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
       
    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain; charset=utf-8")
        self.send_header("Access-Control-Allow-Origin", "*");
        self.send_header("Connection", "close")
        self.end_headers()
        length = int(self.headers['Content-Length'])
        output = json.dumps(("Unknown request",))
        inparam = urlparse.parse_qs(self.rfile.read(length).decode('utf-8'))
        self.do_smth(inparam)

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.send_header("Access-Control-Allow-Origin", "*");
        self.end_headers()
        if len(self.path.split('?'))>1:
            get_data = urlparse.parse_qs(self.path.split('?')[1])
            self.do_smth(get_data)
        else:
            print self.path+" requested"
            if self.path[1:] in self.files:
                a = open(self.path[1:], "r").read().encode()
                self.wfile.write(a)
                if not self.wfile.closed:
                    self.wfile.flush()
                    self.wfile.close()
                self.rfile.close()

    def do_smth(self, inparam):
        print inparam
        res = ''
        if not self.mybook:
            self.mybook = epub("hwjm.epub")
            self.mybook.process_epub()
        if 'toc' in inparam['get']: self.wfile.write(etree.tostring(self.mybook.sel))
        return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

 
if __name__ == '__main__':
    server = ThreadedHTTPServer(('0.0.0.0', 8086), Handler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()

